<template>
  <el-form>
    <el-form-item label="SPU名称">
      <el-input
        placeholder="请你输入SPU名称"
        v-model="spuParams.spuName"
      ></el-input>
    </el-form-item>
    <el-form-item label="SPU品牌">
      <el-select placeholder="请选择" v-model="spuParams.tmId">
        <el-option
          :label="trademark.tmName"
          :value="trademark.id"
          v-for="(trademark, index) in allTradeMarkArr"
          :key="trademark.id"
        ></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="SPU描述">
      <el-input type="textarea" v-model="spuParams.description"></el-input>
    </el-form-item>
    <el-form-item label="SPU图片">
      <el-upload
        :file-list="imgListArr"
        action="/api/admin/product/fileUpload"
        list-type="picture-card"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove"
        :on-success="handleSuccess"
      >
        <el-icon>
          <Plus />
        </el-icon>
      </el-upload>
      <el-dialog v-model="dialogVisible">
        <img :src="dialogImageUrl" alt="Preview Image" style='width:400px; height:400px; margin:0 auto; display:block '/>
      </el-dialog>
    </el-form-item>
    <el-form-item label="销售属性">
      <el-select
        v-model="unSaleAttrIdAndName"
        :placeholder="
          unSelectSaleAttr.length > 0
            ? `你还有${unSelectSaleAttr.length}未选择`
            : `没的选`
        "
      >
        <el-option
          :label="sale.name"
          :value="`${sale.id}:${sale.name}`"
          v-for="(sale, index) in unSelectSaleAttr"
          :key="sale.id"
        ></el-option>
      </el-select>
      <el-button
        style="margin-left: 10px"
        size="default"
        type="primary"
        :icon="Plus"
        :disabled="!unSaleAttrIdAndName"
        @click="addSaleAttr"
        >添加销售属性值</el-button
      >
      <el-table
        border
        stripe
        style="margin: 10px 0px"
        :data="spuHasSaleAttrArr"
      >
        <el-table-column label="序号" type="index" align="center" width="80">
        </el-table-column>
        <el-table-column
          label="属性名"
          width="120px"
          prop="saleAttrName"
        ></el-table-column>
        <el-table-column label="属性值名称列表">
          <template #="{ row, $index }">
            <el-tag
              style="margin: 0px 5px"
              :type="saleValue.id % 2 == 0 ? 'success' : 'warning'"
              v-for="(saleValue, index) in row.spuSaleAttrValueList"
              class="mx - 1"
              :key="saleValue.id"
              closable
              @close="row.spuSaleAttrValueList.splice(index, 1)"
            >
              {{ saleValue.saleAttrValueName }}
            </el-tag>

            <!-- button与input的切换(编辑与查看) -->
            <el-input
              v-model="row.inputValue"
              size="small"
              v-if="row.flag"
              placeholder="请输入属性值"
              style="width: 100px"
              @blur="toLook(row)"
            ></el-input>
            <el-button v-else type="primary" size="small" @click="toEdit(row)" :icon="Plus"></el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120px">
          <template #="{ row, $index }">
            <el-button
              type="danger"
              size="small"
              :icon="Delete"
              @click="spuHasSaleAttrArr.splice($index, 1)">
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-button type="primary" size="default" @click="save">保存</el-button>
      <el-button type="primary" @click="cancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { ref, computed } from "vue";
import { Plus, Delete } from "@element-plus/icons-vue";
import type { UploadProps, UploadUserFile } from "element-plus";
import {ElMessage} from 'element-plus';
//引入请求函数
import {
  reqAllaTradeMark,
  reqAllSaleAttr,
  reqImgList,
  reqSpuHasSaleAttr,
  reqAddOrUpdateSpu,
} from "../../../api/product/spu/spu";

let spuParams = ref<any>({});

//spu 的全部品牌数据
let allTradeMarkArr = ref([]);
//spu下照片墙的数据
let imgListArr = ref([]);
let spuHasSaleAttrArr = ref([]);
let allSaleAttrArr = ref([]);

//存储预览图片
const dialogImageUrl = ref("");
//对话框显示/隐藏
const dialogVisible = ref(false);

let unSaleAttrIdAndName = ref("");

const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  imgListArr.value = uploadFiles;
};

const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!;
  dialogVisible.value = true;
};

//图片上传成功的回调
const handleSuccess = (response, uploadFile, uploadFiles) => {
  imgListArr.value = uploadFiles;
};

const initHasSpuData = async (spu) => {
  spuParams.value = spu;

  let ps1 = reqAllaTradeMark();

  let ps2 = reqImgList(spu.id);

  let ps3 = reqSpuHasSaleAttr(spu.id);

  let ps4 = reqAllSaleAttr();

  let result = await Promise.all([ps1, ps2, ps3, ps4]);

  allTradeMarkArr.value = result[0];

  imgListArr.value = result[1].map((item) => {
    return {
      name: item.imgName,
      url: item.imgUrl,
    };
  });

  spuHasSaleAttrArr.value = result[2];

  allSaleAttrArr.value = result[3];
};

let unSelectSaleAttr = computed(() => {
  let result = allSaleAttrArr.value.filter((item) => {
    return spuHasSaleAttrArr.value.every((item1) => {
      return item.name != item1.saleAttrName;
    });
  });

  return result;
});

//点击添加销售属性按钮回调
const addSaleAttr = () => {
  const [baseSaleAttrId, saleAttrName] = unSaleAttrIdAndName.value.split(":");
  let newSaleAttr = { baseSaleAttrId, saleAttrName, spuSaleAttrValueList: [] };
  spuHasSaleAttrArr.value.push(newSaleAttr);
  //清空下拉框
  unSaleAttrIdAndName.value = "";
};

// 点击按钮变为编辑模式
const toEdit = (row)=>{
  row.flag=true;
  row.inputValue='';
};
//input失去焦点
const toLook=(row)=>{
  if(row.inputValue.trim()==''){
    ElMessage({
      type: 'error',
      message:'属性值不能为空'
    });
    return;
  }
  //属性值不能与前面已有的重复
  let repeat = row.spuSaleAttrValueList.find(item=>{
    return item.saleAttrValueName===row.inputValue;
  });
  if(repeat){
    ElMessage({
      type:'error',
      message:'属性值名称不能重复',
    });
    //清空同名属性值
    row.inputValue = '';
    row.flag=false;
    return;
  }
  row.flag= false;
  let newSaleattrVal={
    baseSaleAttrId:row.baseSaleAttrId,
    saleAttrValueName:row.inputValue,
  };
  row.spuSaleAttrValueList.push(newSaleattrVal);
row.inputValue='';
};
//按钮保存事件回调
const save =async()=>{
  spuParams.value.spuImageList =imgListArr.value.map((item)=>{
  return{
    imgName:item.name,
    imgUrl:(item.response&&item.response.data)||item.url,
  };
});
spuParams.value.spuSaleAttrList =spuHasSaleAttrArr.value;
try{
  await reqAddOrUpdateSpu(spuParams.value);
  ElMessage({
    type:'success',
    message:spuParams.value.id?'修改成功':'添加成功',
  });

  emit("changeScene",{
    scenes:0,
    flag:spuParams.value.id?'update':'add',
  });

  resetData();
}catch(error){
  ElMessage({
    type:'error',
    message:spuParams.value.id?'修改失败':'添加失败',
  });
}
};

//取消
const cancel = () => {
  emit("changeScene", {
    scenes: 0,
    flag: spuParams.value.id ? "update" : "add",
  });
  resetData();
};

//清空数据
const resetData =()=> {
  spuParams.value = {};
  imgListArr.value =[];
  spuHasSaleAttrArr.value=[];
};

const initAddSpu= async (c3Id:string|number)=>{
  spuParams.value.category3Id=c3Id;
  let ps1=reqAllaTradeMark();
  let ps2=reqAllSaleAttr();
  let result =await Promise.all([ps1,ps2]);
  allTradeMarkArr.value=result[0];
  allSaleAttrArr.value= result[1];
};

//触发自定义事件
let emit = defineEmits(["changeScene"]);

//对外暴露
defineExpose({
  initHasSpuData,
  initAddSpu,
});
</script>

<style scoped>
</style>